package com.sky.controller.admin;

import com.aliyuncs.http.HttpRequest;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.apache.bcel.generic.TABLESWITCH;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("员工登录接口")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("员工登出接口")
    public Result<String> logout() {
        BaseContext.removeCurrentId();
        return Result.success();
    }


    /**
     * 新增员工
     */
    @PostMapping
    @ApiOperation("新增员工")
    public Result addEmployee(@RequestBody EmployeeDTO employeeDTO, HttpServletRequest request){
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // TODO 创建人、更新人id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        // 查看用户是否已经存在
        if(employeeService.findEmployeeByUsername(employee) == null){
            employeeService.addEmployee(employee);
            return Result.success();
        }
        return Result.error(MessageConstant.ACCOUNT_IS);
    }

    /**
     * 员工分页
     */
    @GetMapping("/page")
    @ApiOperation("员工分页查询")
    public Result<PageResult> employPage(EmployeePageQueryDTO employeePageQueryDTO){
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeService.employPage(employeePageQueryDTO);
        List<Employee> employeeList = page.getResult();
        PageResult pageResult = new PageResult(page.getTotal(), employeeList);
        return Result.success(pageResult);
    }

    /**
     * 员工禁用
     */

    @PostMapping(value = "/status/{status}")
    @ApiOperation("员工禁用")
    public Result startEmployStatus(@PathVariable Integer status, Long id){
        employeeService.startEmployStatus(status, id);
        return Result.success();
    }


    /**
     * 修改密码
     * @param status
     * @param id
     * @return
     */
    @PutMapping(value = "/editPassword")
    @ApiOperation("修改密码")
    public Result updateEmployPassword(@RequestBody PasswordEditDTO passwordEditDTO){
        return employeeService.updateEmployPassword(passwordEditDTO);
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}")
    @ApiOperation("根据id查询员工")
    public Result queryByEmployId(@PathVariable Long id){
        return employeeService.queryByEmployId(id);
    }


    /**
     * 编辑员工信息
     * @param id
     * @return
     */
    @PutMapping
    @ApiOperation("编辑员工信息")
    public Result updateEmployId(@RequestBody EmployeeDTO employeeDTO){
        return employeeService.updateEmployId(employeeDTO);
    }
}
